﻿using System.ComponentModel;

namespace CommonTools.Extension;

/// <summary>
/// 枚举扩展方法类
/// </summary>
public static class EnumExtension
{
    private static Dictionary<string, Dictionary<string, string>> enumCache = new();

    private static Dictionary<string, Dictionary<string, string>> EnumCache
    {
        get { return enumCache ??= new Dictionary<string, Dictionary<string, string>>(); }
        set => enumCache = value;
    }

    /// <summary>
    /// 枚举扩展方法
    /// </summary>
    /// <param name="en"></param>
    /// <returns></returns>
    public static string GetEnumText(this Enum en)
    {
        string enString = string.Empty;
        if (null == en) return enString;
        var type = en.GetType();
        enString = en.ToString();
        if (type.FullName != null && !EnumCache.ContainsKey(type.FullName))
        {
            var fields = type.GetFields();
            Dictionary<string, string> temp = new Dictionary<string, string>();
            foreach (var item in fields)
            {
                var attrs = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs.Length == 1)
                {
                    var v = ((DescriptionAttribute)attrs[0]).Description;
                    temp.TryAdd(item.Name, v);
                }
            }
            EnumCache.TryAdd(type.FullName, temp);
        }
        if (type.FullName != null && EnumCache[type.FullName].ContainsKey(enString))
        {
            return EnumCache[type.FullName][enString];
        }
        return enString;
    }

}